package com.lyy.lottery.common.util;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;

import java.util.List;
import java.util.concurrent.Callable;

//封装 Jackson 库的 ObjectMapper 的使用，提供了 JSON 序列化和反序列化的方法

public class JacksonUtil {
    public JacksonUtil() {
    }

    //单例模式
    private final static ObjectMapper OBJECT_MAPPER;
    static {
        OBJECT_MAPPER=new ObjectMapper();
    }

    public static ObjectMapper getObjectMapper(){
        return OBJECT_MAPPER;
    }

    private static <T> T tryParse(Callable<T> parser){
        return tryParse(parser, JacksonException.class);
    }

    private static <T> T tryParse(Callable<T> parser, Class<? extends Exception> check){
        try {
            return parser.call();
        } catch (Exception e) {
            if (check.isAssignableFrom(e.getClass())){
                throw new JsonParseException(e);
            }
            throw new IllegalStateException(e);
        }
    }

    //序列化
    public static String writeValueAsString(Object value){
        return JacksonUtil.tryParse(()->
                JacksonUtil.getObjectMapper().writeValueAsString(value));
    }

    //反序列化
    public static <T> T readValue(String content,Class<T> valueType){
        return JacksonUtil.tryParse(()->
                JacksonUtil.getObjectMapper().readValue(content,valueType));
    }

    //反序列化List
    //Class<T> parameterClasses表示 List 中元素的类型
    public static <T> T readListValue(String content,Class<?> parameterClasses){
        return JacksonUtil.tryParse(()->
                JacksonUtil.getObjectMapper().readValue(content,
                        JacksonUtil.getObjectMapper().getTypeFactory().constructParametricType(List.class,parameterClasses)));
    }
}
